package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.health.dao.MenuDao;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.PermissionDao;
import com.itheima.health.dao.RoleDao;
import com.itheima.health.dao.UserDao;
import com.itheima.health.pojo.Menu;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import java.util.*;

/**
 * @author zhangmeng
 * @description 用户服务实现类
 * @date 2019/9/6
 **/
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private MenuDao menuDao;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public User findByUsername(String username) {
        //先访问redis 判断是否存在user
        User redisUser = (User) redisTemplate.opsForValue().get((username));
        if (null!=redisUser){
            log.debug("[redisUser]data:{}",redisUser);
            return redisUser;
        }
        //先查基本信息

        //先查询redis中是否有user对象(redis中存储为key-hash(hashkey,value))
        User userRedis = (User) redisTemplate.opsForHash().get("userKey",username);
        if (null != userRedis){
            log.info("userRedis:{}",userRedis);
            return userRedis;
        }
        //如果redis中不存在对应的user
        //查询查询数据库，先查基本信息
        User user = userDao.selectByUsername(username);
        if (null == user) {
            //用户不存在
            return null;
        }
        //用户存在，封装到hashMap中，以唯一的username作为key
        HashMap<String,User> userMap = new HashMap<>();
        //根据用户ID查角色信息
        List<Role> roles = roleDao.selectByUserId(user.getId());
        for (Role role : roles) {
            //根据角色ID查权限信息
            List<Permission> permissions = permissionDao.selectByRoleId(role.getId());
            role.getPermissions().addAll(permissions);
        }
        user.getRoles().addAll(roles);
        userMap.put(user.getUsername(),user);
        //把user放到redis中
        redisTemplate.opsForHash().putAll("userKey",userMap);
        log.info("[查询成功]User:{}",user);
        //设置redis的缓存时间以及把数据存入redis
        redisTemplate.opsForValue().set(user.getUsername(),user,10, TimeUnit.SECONDS);
        return user;
    }

    /**
     * 根据用户名查询用户权限角色
     * @param username
     * @return
     */
    @Override
    public List<Long> getRoleIdByUsername(String username) {
        User user = userDao.selectByUsername(username);
        return roleDao.selectRoleIdByUserId(user.getId());


    }


    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //设置分页参数
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //DAO查询数据
        Page<User> page = userDao.selectByCondition(queryPageBean.getQueryString());
        //封装返回值
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 增加用户
     * @param user
     * @param roles
     */
    @Override
    public void add(User user, Integer[] roles) {
        log.info("[用户-添加]data:{},roles:{}",user,roles);
        // 调用DAO数据入库
        //将密码进行加密
        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
        String password = bc.encode(user.getPassword());
        user.setPassword(password);
        // 插入基本数据
        userDao.insert(user);
        // 插入关联数据
        for (Integer role : roles) {
            userDao.insertUserAndRole(user.getId(),role);
        }
    }

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @Override
    public User findById(Integer id) {
        //调用Dao查询
        return userDao.queryById(id);
    }

    /**
     * 根据用户id查询角色id
     * @param id
     * @return
     */
    @Override
    public List<Integer> findRoleIdByUserId(Integer id) {
        //DAO查询
        List<Integer> ins = userDao.queryRoleIdByUserId(id);
        return ins;
    }

    /**
     * 编辑用户
     * @param user
     * @param roleIds
     */
    @Override
    public void editByUserAndRoleIds(User user, Integer[] roleIds) {
        log.info("[用户-编辑]data:{},checkitemIds:{}", user, roleIds);
        //DAO编辑
        userDao.updateByUserAndRoleIds(user);
        //更改用户和角色的关系
        //先清除原有的关系
        userDao.delectByUserId(user.getId());
        //添加新的关系
        for (Integer roleId : roleIds) {
            userDao.insertUserAndRole(user.getId(),roleId);
        }
    }

    /**
     * 删除用户
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        //DAO删除
        //先删除用户和角色的关系
        userDao.delectByUserId(id);
        //删除用户
        userDao.delect(id);
    }

    /**
     * 检查用户名是否存在
     * @param username
     * @return
     */
    @Override
    public User checkUsername(String username) {
        //DAO查询
        return userDao.checkByUsername(username);
    }

    /**
     * 修改用户密码
     * @param username
     * @param password
     * @param newPassword
     */
    @Override
    public void updatePassword(String username, String newPassword) {
        userDao.updatePassword(username,newPassword);
    }
}
